package com.micai.springboot.realm;

import com.micai.springboot.domain.Module;
import com.micai.springboot.domain.Role;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.micai.springboot.domain.User;
import com.micai.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 描述：
 * <p>
 * Author: 赵新国
 * Date: 2017/11/7 16:21
 */
public class AuthRealm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(AuthRealm.class);

    @Autowired
    private UserService userService;

    /**
     * 认证，登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户输入的token
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        // 查出是否有此用户
        User user = userService.findUserByUserName(utoken.getUsername());
        // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取session中的用户
        User user = (User) principals.fromRealm(this.getClass().getName()).iterator().next();
        List<String> permissions = new ArrayList<String>();
        Set<Role> roles = user.getRoles();
        if (roles.size() > 0) {
            for (Role role : roles) {
                Set<Module> modules = role.getModules();
                if (modules.size() > 0) {
                    for (Module module : modules) {
                        permissions.add(module.getMname());
                    }
                }
            }
        }
        // 将权限放入shiro中
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);
        return info;
    }

}
